package com.woniu.handler;

import cn.hutool.json.JSONUtil;
import com.woniu.utils.ResData;
import com.woniu.utils.WebFluxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class LogoutSuccessHandler implements ServerLogoutSuccessHandler {
    @Autowired
    ReactiveStringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> onLogoutSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {

        String token = webFilterExchange.getExchange().getRequest().getHeaders().getFirst("JWToken");

        return redisTemplate.opsForValue()
                .delete("JWToken:" + token)
                .flatMap((result) -> {
                    ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

                    return response.writeWith(
                            Mono.just(
                                    response.bufferFactory().wrap(
                                            JSONUtil.toJsonStr(
                                                    ResData.success("注销成功")
                                            ).getBytes(StandardCharsets.UTF_8)
                                    )
                            )
                    );
                });
    }


}
